<template>
  <div class="home" v-bind:class="{ minH: minH }">
    <div>
      <img src="../assets/home_bg.jpg" alt="" />
    </div>
    <div class="selTeam">
      <div
        class="selItem"
        v-bind:class="{ active: team == 1 }"
        @click="team = 1"
      >
        <img :src="activity.douwu_left_logo" alt="" />
      </div>
      <div
        class="selItem"
        v-bind:class="{ active: team == 2 }"
        @click="team = 2"
      >
        <img :src="activity.douwu_right_logo" alt="" />
      </div>
    </div>
    <div class="choseTip">请选择你要加入的队伍</div>
    <div class="btnview">
      <div v-show="activity.state == 1" class="btn" @click="setDeviceMotion">
        开始挑战
      </div>
      <div v-show="activity.state != 1" class="btn btndis">
        活动结束
      </div>
    </div>
    <div class="rule" @click="open">
      查看规则
    </div>
    <div class="paybg" v-show="showPay" @click="hidePay">
      <div class="paybottom" @click.stop="dd">
        <div class="cash" v-show="radio == 1">￥{{ activity.price }}元</div>
        <div class="cash" v-show="radio == 3">￥{{ activity.ratio }}积分</div>
        <div class="ops">
          <div class="radiogroup">
            <el-radio v-model="radio" label="1" class="eradio"
              >微信支付</el-radio
            >
            <el-radio :disabled="jfpay" v-model="radio" label="3"
              >积分支付</el-radio
            >
          </div>
          <div class="gopay" @click="goPay">去支付</div>
        </div>
      </div>
    </div>
    <div class="gamebg" v-show="showGame">
      <div class="gameBox">
        <p class="title">手机摇一摇，为团队加分</p>
        <img src="../assets/shank.png" v-bind:class="{ active: showGame }" />
        <p class="tips"><span>温馨提示</span>摇动手机时，请注意安全哦</p>
      </div>
    </div>
    <div class="prizebg" v-show="showPrize">
      <div
        class="prizeBox"
        :style="{ backgroundImage: `url(${activity.mobile_douwu_lottery})` }"
      >
        <div class="teamBox">
          <img
            :src="activity.douwu_left_logo"
            class="teamHead"
            v-bind:class="{ active: rank.result == 1 }"
          />
          <img
            :src="activity.douwu_right_logo"
            class="teamHead"
            v-bind:class="{ active: rank.result == 2 }"
          />
          <img
            class="winIcon winIconLeft"
            src="../assets/win.png"
            v-show="rank.result == 1"
          />
          <img
            class="winIcon winIconRight"
            src="../assets/win.png"
            v-show="rank.result == 2"
          />
        </div>
        <div class="winTxt" v-show="rank.result == 1">
          {{ activity.douwu_left_title }}获胜。<span v-show="perPeize.prize"
            >恭喜您获得幸运奖“{{ perPeize.prize }}”</span
          >
        </div>
        <div class="winTxt" v-show="rank.result == 2">
          {{ activity.douwu_right_title }}获胜。<span v-show="perPeize.prize"
            >恭喜您获得幸运奖“{{ perPeize.prize }}”</span
          >
        </div>
        <div class="per_prize">
          <img :src="perPeize.avator" class="header" />
          <p class="userName">{{ perPeize.nickname }}</p>
          <p class="userScore">分数 {{ perPeize.score }}</p>
          <p class="userRank">排名 {{ perPeize.rank }}</p>
          <img
            v-show="perPeize.prize_id != 0"
            :src="perPeize.prize_img"
            class="prize_img"
          />
          <p class="prize_name">{{ perPeize.prize }}</p>
        </div>
      </div>
      <a href="https://m.hangzhouhaiyu.com/#/list" class="seePrize">查看奖品</a>
      <div @click="showPrize = false" class="btn_again">
        再来一局
      </div>
    </div>
    <audio src="../assets/bgm.mp3" class="audio" loop></audio>
  </div>
</template>

<script>
import weixin from '@/utils/weixin';
// @ is an alias to /src
export default {
  name: 'home',
  components: {},
  data() {
    return {
      $audio: document.getElementsByClassName('audio')[0],
      docmHeight: document.documentElement.clientHeight, //默认屏幕高度
      docmWidth: document.documentElement.clientWidth,
      minH: false,
      team: 0,
      radio: '1',
      showGame: false,
      showPay: false,
      activityid: null,
      userinfo: null,
      activity: {
        ratio: 0,
        price: '2',
      },
      order_id: '',
      mobile_login: '',
      jfpay: true,
      SHAKE_THRESHOLD: 2000, //定义一个摇动的值
      last_update: 0, //定义一个变量保存上次更新的时间
      x: 0, //定义xyz记录三个轴的数据以及上一次出发的时间
      y: 0,
      z: 0,
      last_x: 0,
      last_y: 0,
      last_z: 0,
      count: 0, //次数
      lefttime: 0,
      isCanYao: false,
      sendInter: null,
      isCanPlay: true,
      showPrize: false,
      rank: {
        result: 1,
        jia: {
          score: 10,
          num: 2,
        },
        yi: {
          score: 10,
          num: 2,
        },
        team_list: [],
        person_list: [],
      },
      perPeize: {
        prize_id: 0,
        prize: '',
      },
      interval_time: 10,
    };
  },
  mounted() {
    var sca = this.docmWidth / this.docmHeight;
    if (sca > 0.58) {
      this.minH = true;
    }
    if (this.$route.query.activityid) {
      this.activityid = this.$route.query.activityid;
    } else {
      this.$toast('活动已结束');
    }
    this.init();
  },
  methods: {
    init() {
      this.getActivityInfo();
      if (this.$route.query.openID) {
        localStorage['openid'] = this.$route.query.openID;
      }
      if (this.$route.query.mobile_login) {
        this.mobile_login = this.$route.query.mobile_login;
      }
      if (this.$route.query.token) {
        localStorage['token'] = this.$route.query.token;
      }
    },
    setDeviceMotion() {
      var that = this;
      if (!window.DeviceMotionEvent) {
        that.getActivityInfo(1);
        return;
      }
      if (typeof DeviceMotionEvent.requestPermission === 'function') {
        DeviceMotionEvent.requestPermission()
          .then(permissionState => {
            if (permissionState === 'granted') {
              that.isCanYao = true;
              window.addEventListener(
                'devicemotion',
                that.deviceMotionHandler,
                false
              );
            }
          })
          .catch(err => {
            this.$toast('用户未开启权限');
          });
      } else {
        // 其他支持加速度检测的系统
        let timer = setTimeout(function() {
          this.$toast('用户未开启权限');
        }, 1000);
        window.addEventListener(
          'devicemotion',
          e => {
            clearTimeout(timer);
          },
          { once: true }
        );
        that.isCanYao = true;
        window.addEventListener(
          'devicemotion',
          that.deviceMotionHandler,
          false
        );
      }
      that.getActivityInfo(1);
      console.log('是否可以摇一摇', that.isCanYao);
    },
    goPlay() {
      if (this.$route.query.activityid) {
        this.activityid = this.$route.query.activityid;
      } else {
        this.$toast('活动已结束');
        return;
      }
      if (this.activity.douwu_is_open == 0) {
        this.$toast('大奖正在准备中，稍等哦！');
        return false;
      }
      if (this.lefttime <= 5) {
        this.$toast('这一轮即将开奖，请稍后参与下一轮哦！');
        return false;
      }
      this.isCanPlay = true;
      if (this.activity.pay_state == 2 && this.activity.state == 1) {
        this.getActivityInfo(2);
        return;
      }
      if (this.team == 0) {
        this.$toast('请选择你要加入的队伍');
        return false;
      }

      // 已登录 获取手机号
      if (localStorage['mobile']) {
        if (parseFloat(this.activity.price) <= 0) {
          this.goPay();
        } else {
          this.showPay = true;
        }

        if (!this.userinfo) {
          this.getUserInfo();
        }
        return;
      }

      // 需要手机验证，该用户为手机验证
      if (this.mobile_login != 1 && this.activity.mobile_verify == 1) {
        this.$api
          .logintype({ activity_id: this.activityid })
          .then(res => {
            if (res.code == 200) {
              if (res.data.type == 2) {
                this.$router.push({
                  name: 'login',
                  query: {
                    activityid: this.activityid,
                    logo: res.data.logo,
                    name: res.data.market_name,
                  },
                });
              } else {
                this.$api.gomallcoologin(
                  this.activityid,
                  localStorage['openid']
                );
              }
            } else {
              this.$toast(res.message);
            }
          })
          .catch(err => {
            this.$toast('网络错误');
          });
      } else {
        if (!this.userinfo) {
          this.getUserInfo();
        }
        if (parseFloat(this.activity.price) <= 0) {
          this.goPay();
        } else {
          this.showPay = true;
        }
      }
    },
    gameInit() {
      var that = this;
      this.showGame = true;
      if (this.sendInter) {
        clearInterval(this.sendInter);
      }
      var $audio = document.getElementsByClassName('audio')[0];
      $audio.play();
      this.sendInter = setInterval(() => {
        if (that.isCanYao) {
          that.count = 50 + Math.floor(Math.random() * 50);
        }
        that.sendScore();
        that.lefttime = that.lefttime - 2;
        console.log(that.lefttime);
        if (that.lefttime <= 0 || that.lefttime >= that.activity.douwu_time) {
          $audio.pause();
          this.isCanPlay = false;
          clearInterval(this.sendInter);
          that.showGame = false;
          that.$loading('正在加载...');
          setTimeout(function() {
            that.getResult();
          }, 2500);
        }
      }, 2000);
    },
    deviceMotionHandler(eventData) {
      let acceleration = eventData.accelerationIncludingGravity; //含重力加速度
      let curTime = new Date().getTime(); //获取当前时间
      if (curTime - this.last_update > 10) {
        //curTime - last_update 是固定时间段
        let diffTime = curTime - this.last_update;
        this.last_update = curTime;
        this.x = acceleration.x;
        this.y = acceleration.y;
        this.z = acceleration.z;
        let speed =
          (Math.abs(
            this.x + this.y + this.z - this.last_x - this.last_y - this.last_z
          ) /
            diffTime) *
          10000;
        if (speed > this.SHAKE_THRESHOLD) {
          this.count++; //次数自增1
        }
        this.last_x = this.x;
        this.last_y = this.y;
        this.last_z = this.z;
      }
    },
    sendTeam() {
      var that = this;
      that.$api
        .douwuCheckTeam({
          activity_id: that.activityid,
          team: that.team,
          sequence: that.activity.now_sequence,
        })
        .then(res => {
          if (res.code == 200) {
            that.gameInit();
          } else if (res.code == 405) {
            that.$toast('本局即将开奖，请稍等参加下一局哦！');
          } else {
            that.$toast(res.message);
          }
        })
        .catch(err => {});
    },
    sendScore() {
      var that = this;
      if (!this.isCanPlay) {
        clearInterval(this.sendInter);
        return false;
      }
      console.log('提交的分数', this.count);
      if (!this.order_id || this.team == 0) {
        return;
      }
      that.$api
        .saveScore({
          activity_id: this.activityid,
          team: this.team,
          sequence: this.activity.now_sequence,
          order_id: this.order_id,
          score: this.$yy.encrypt(this.count),
        })
        .then(res => {
          if (res.code == 200) {
            that.count = 0;
          } else {
            that.showGame = false;
            if (
              res.message.indexOf('本轮活动未开始或者已结束') > -1 ||
              res.message.indexOf('本轮活动已经结束') > -1
            ) {
              var $audio = document.getElementsByClassName('audio')[0];
              $audio.pause();
              clearInterval(this.sendInter);
              this.isCanPlay = false;
              that.$loading('正在加载...');
              setTimeout(function() {
                that.getResult();
              }, 2500);
              return false;
            } else {
              this.$toast(res.message);
            }
          }
        })
        .catch(err => {});
    },
    getResult() {
      var that = this;
      // console.log(this.user);
      that.$api
        .resultList({
          activity_id: this.activityid,
          sequence: this.activity.now_sequence,
          member_id: this.userinfo.member_id,
        })
        .then(res => {
          if (res.code == 200) {
            that.rank = res.data;
            that.perPeize = res.data.member;
            that.$loading().close();
            that.showPrize = true;
          } else {
            this.$toast(res.message);
          }
        })
        .catch(err => {});
    },
    getUserInfo() {
      this.$api
        .userinfo({ activity_id: this.activityid })
        .then(res => {
          if (res.code == 200) {
            this.userinfo = res.data;
            localStorage['user'] = JSON.stringify(this.userinfo);
            this.activity.ratio = this.activity.price / res.data.ratio;
            console.log(res.data.ratio, this.activity.ratio);
            if (this.activity.ratio_credit == 0 || res.data.score == 0) {
              this.jfpay = true;
            } else if (this.activity.ratio_credit != 0 && res.data.score > 0) {
              this.jfpay = false;
            }
          } else {
            if (res.code == 401) {
              localStorage.removeItem('mobile');
            }
          }
        })
        .catch(err => {});
    },
    hidePay() {
      this.showPay = false;
    },
    getActivityInfo(status) {
      this.$loading('正在加载...');
      var that = this;
      this.$api
        .douwuinfo({ activity_id: this.activityid })
        .then(res => {
          this.$loading().close();
          if (res.code == 200) {
            this.activity = res.data;
            document.title = this.activity.activity_name;

            this.interval_time = this.activity.interval_time;
            var endtime = new Date(that.activity.next_sequence_time); //结束时间
            var nowtime = new Date(that.activity.system_time); //当前时间
            that.lefttime =
              parseInt((endtime.getTime() - nowtime.getTime()) / 1000) -
              Number(this.interval_time);

            this.getUserInfo();
            /* eslint-disable no-undef */
            weixin.wxShare(wx, this.activity);
            if (status && status == 1) {
              that.goPlay();
            } else if (status && status == 2) {
              that.sendTeam();
            }
          } else {
            this.$toast(res.message);
            if (res.code == 401) {
              localStorage.removeItem('mobile');
            }
          }
        })
        .catch(err => {
          that.$loading().close();
        });
    },
    goPay() {
      this.$loading('正在加载...');
      var that = this;
      that.$api
        .createOrder({
          activity_id: that.activityid,
          point: that.radio == 3 ? that.activity.ratio : 0,
          trade_type: that.radio,
          open_id: localStorage['openid'],
          type: 2,
          now_sequence: that.activity.now_sequence,
        })
        .then(res => {
          that.$loading().close();
          if (res.code == 200) {
            that.order_id = res.data.order_id;
            if (res.data.status == 2) {
              //不需要支付或积分支付成功
              that.hidePay();
              that.getActivityInfo(2);
            } else {
              // 微信支付
              that.wechatPay(res.data);
            }
          } else {
            that.$toast(res.message);
            if (res.code == 401) {
              that.$router.push({
                name: 'login',
                query: {
                  activityid: this.activityid,
                  logo: this.activity.market.logo,
                  name: this.activity.market.market_name,
                },
              });
            }
          }
        })
        .catch(err => {
          that.$loading().close();
        });
    },
    wechatPay(data) {
      var that = this;
      WeixinJSBridge.invoke('getBrandWCPayRequest', data.wx, function(res) {
        console.log(res);
        if (res.err_msg == 'get_brand_wcpay_request:ok') {
          //微信支付成功
          that.hidePay();
          that.getActivityInfo(2);
        } else {
          that.$toast('支付失败，请稍后重试');
        }
      });
    },
    open() {
      this.$notify.closeAll();
      this.$notify({
        dangerouslyUseHTMLString: true,
        message: this.activity.desc.replace(/\r\n/g, '<br>'),
        duration: 0,
        customClass: 'el-notifyqqq',
        offset: 100,
      });
    },
  },
};
</script>

<style lang="scss">
.el-notifyqqq {
  left: calc((100vw - 330px) / 2);
}
.home {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;

  img {
    width: 100%;
    height: 100%;
  }
  .ranking {
    margin-top: 12px;
    text-decoration: underline #333333;
    font-size: 30px;
  }
  &.minH {
    .selTeam {
      top: 112vw;
    }
    .choseTip {
      top: 810px;
    }
    .btnview {
      top: 1000px;
    }
  }
}
.selTeam {
  position: absolute;
  width: 57.3vw;
  height: 20.26vw;
  display: flex;
  justify-content: space-between;
  top: 112vw;
  left: 50%;
  margin-left: -28.65vw;
  .selItem {
    width: 20.26vw;
    height: 20.26vw;
    text-align: center;
    line-height: 20.26vw;
    position: relative;
    border-radius: 15px;
    opacity: 0.7;
    img {
      width: 20.26vw;
      height: 20.26vw;
    }
    &.active {
      opacity: 1;
    }
  }
}
.choseTip {
  width: 100%;
  font-size: 24px;
  color: #ec5cdd;
  position: absolute;
  top: 1030px;
}
.btnview {
  position: absolute;
  top: 1100px;
  width: 100%;
  height: 130px;
}
.btn {
  color: #fff;
  font-size: 40px;
  line-height: 130px;
  margin: 0 auto;
  width: 508px;
  height: 130px;
  background-image: url(../assets/btn_start.png);
  background-size: 100% 100%;
}
.rule {
  position: absolute;
  right: 30px;
  top: 20px;
  font-size: 30px;
  color: #ec5cdd;
}
.paybg {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  background: rgba(0, 0, 0, 0.4);
  .paybottom {
    position: absolute;
    bottom: 0;
    display: flex;
    width: 100%;
    flex-direction: column;
    align-content: center;
    padding: 50px 40px;
    padding-top: 30px;
    background: white;
    .cash {
      font-weight: bold;
      font-size: 60px;
      color: #444444;
      border-bottom: #ebebeb 1px solid;
      margin-bottom: 40px;
      line-height: 120px;
    }
    .ops {
      padding: 0 150px;
    }
    .radiogroup {
      display: flex;
      flex-direction: column;
      align-content: flex-start;
      align-items: flex-start;
      color: #666666;
      .el-radio__input.is-checked + .el-radio__label {
        color: #666666;
      }
      .el-radio__input.is-checked .el-radio__inner {
        border-color: #f54e49;
        background: #f54e49;
      }
    }
    .eradio {
      margin-bottom: 40px;
    }
    .gopay {
      margin-top: 40px;
      height: 80px;
      background-image: linear-gradient(
        0deg,
        #f36865 1%,
        #f54845 16%,
        #f39090 100%
      );
      box-shadow: 0px 10px 30px 0px rgba(0, 0, 0, 0.4);
      border-radius: 45px;
      line-height: 80px;
      color: white;
    }
  }
}
.gamebg {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  background: rgba(0, 0, 0, 0.8);
  .gameBox {
    width: 548px;
    height: 900px;
    background: url(../assets/game.png);
    background-size: 100% 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -450px 0 0 -274px;
    .title {
      text-align: center;
      width: 100%;
      height: 42px;
      font-size: 40px;
      font-weight: bold;
      color: #fff;
      line-height: 42px;
      margin-top: 92px;
    }
    img {
      width: 364px;
      height: 450px;
      margin: 100px auto;
      &.active {
        animation: rotates 1s linear infinite;
      }
    }
    @keyframes rotates {
      0%,
      75% {
        transform: rotate(0deg);
      }
      80% {
        transform: rotate(10deg);
      }
      85% {
        transform: rotate(-10deg);
      }
      90% {
        transform: rotate(10deg);
      }
      95% {
        transform: rotate(-10deg);
      }
      100% {
        transform: rotate(0deg);
      }
    }
    .tips {
      text-align: center;
      font-size: 24px;
      color: #29c4fe;
      line-height: 40px;
      span {
        display: block;
        font-weight: bold;
      }
    }
  }
}
.prizebg {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  background: rgba(0, 0, 0, 0.8);
  .prizeBox {
    width: 610px;
    height: 918px;
    background-repeat: no-repeat;
    background-size: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -60%);
    .teamBox {
      width: 414px;
      height: 124px;
      display: flex;
      justify-content: space-between;
      margin: 226px auto 0;
      position: relative;
      .teamHead {
        width: 124px;
        height: 124px;
        opacity: 0.7;
        &.active {
          opacity: 1;
        }
      }
      .winIcon {
        position: absolute;
        width: 98px;
        height: 71px;
        top: -42px;
        left: 62px;
        &Right {
          left: 352px;
        }
      }
    }
    .winTxt {
      font-size: 26px;
      line-height: 36px;
      color: #fff;
      text-align: center;
      width: 490px;
      margin: 10px auto 0;
    }
    .per_prize {
      width: 490px;
      height: 368px;
      position: relative;
      margin: 70px auto 0;
      background: url(../assets/per_prize_bg.png) no-repeat;
      background-size: 100%;
      .header {
        width: 100px;
        height: 100px;
        position: absolute;
        top: 48px;
        left: 40px;
        border-radius: 50px;
        border: 1px solid #fff;
      }
      .userName {
        color: #fff;
        font-size: 26px;
        position: absolute;
        height: 26px;
        top: 180px;
        left: 40px;
        font-weight: bold;
      }
      .userScore,
      .userRank {
        color: #fff;
        font-size: 26px;
        position: absolute;
        height: 30px;
        line-height: 30px;
        top: 240px;
        left: 40px;
        padding-left: 43px;
        background: url(../assets/fs_ico.png) left center no-repeat;
        background-size: 30px auto;
      }
      .userRank {
        top: 294px;
        background-image: url(../assets/pm_ico.png);
      }
      .prize_img {
        position: absolute;
        top: 156px;
        left: 308px;
        width: 124px;
        height: 124px;
        border: 1px solid #fff;
        border-radius: 7px;
      }
      .prize_name {
        color: #fff;
        font-size: 26px;
        position: absolute;
        width: 260px;
        left: 230px;
        top: 308px;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
  .seePrize {
    width: 280px;
    height: 90px;
    box-sizing: border-box;
    line-height: 84px;
    border-radius: 10px;
    border: 3px solid #29c4fe;
    background: #000;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: 420px 0 0 -300px;
    text-align: center;
    color: #29c4fe;
    font-size: 40px;
    letter-spacing: 5px;
  }
  .btn_again {
    width: 320px;
    height: 130px;
    background: url(../assets/btn_again.png) no-repeat;
    background-size: 100% 100%;
    font-size: 0;
    position: absolute;
    left: 50%;
    top: 50%;
    margin: 400px 0 0 5px;
  }
}
</style>
